<template>
    <div>
        <div class="w-form-header">
            <!-- <span>
                {{ type == "create" ? "创建款式" : "修改款式" }}
            </span> -->
            <div>
                <el-button
                    type="primary"
                    @click="save('0')"
                    :loading="saveLoading"
                    >保存</el-button
                >
                <el-button
                    type="success"
                    @click="save('1')"
                    :loading="submitLoading"
                    >提交</el-button
                >
            </div>
        </div>
        <div class="admin-content">
            <div class="gva-form-box">
                <div class="w-form-box">
                    <div class="list-header">基础信息</div>
                    <el-form
                        :model="formData"
                        ref="elFormRef"
                        label-position="right"
                        :rules="rule"
                        label-width="90px"
                        :inline="true"
                        class="form-inline"
                    >
                        <!-- 项目编号 -->
                        <el-form-item
                            :label="`${il8n('xiangmubianhao.label')}:`"
                            prop="projectNum"
                        >
                            <el-select
                                v-model="formData.projectNum"
                                :placeholder="`${il8n(
                                    'xiangmubianhao.placeholder'
                                )}`"
                                style="width: 100%"
                                filterable
                                remote
                                :remote-method="remoteMethodProject"
                                @change="projectNumChange"
                            >
                                <el-option
                                    v-for="(item, key) in projectListOptions"
                                    :key="key"
                                    :label="item.projectNum"
                                    :value="item.projectNum"
                                />
                            </el-select>
                        </el-form-item>
                        <!-- 款式编号 -->
                        <el-form-item
                            :label="`${il8n('kuanshibianhao1.label')}:`"
                            prop="styleNum"
                        >
                            <el-input
                                v-model="formData.styleNum"
                                :clearable="true"
                                :placeholder="`${il8n(
                                    'kuanshibianhao1.placeholder'
                                )}`"
                                disabled
                            />
                        </el-form-item>
                        <!-- 本厂款号 -->
                        <el-form-item
                            :label="`${il8n('benchangkuanhao.label')}:`"
                            prop="localStyleNum"
                        >
                            <div
                                style="
                                    display: flex;
                                    just-content: center;
                                    align-items: center;
                                    width: 100%;
                                    justify-content: space-between;
                                "
                            >
                                <el-input
                                    v-model="formData.localStyleNum"
                                    :clearable="true"
                                    :placeholder="`${il8n(
                                        'benchangkuanhao.placeholder'
                                    )}`"
                                    disabled
                                />
                                <el-button
                                    type="primary"
                                    size="small"
                                    style="padding: 15px 6px"
                                    @click="getGenLocalStyleNumFun"
                                    :disabled="!!formData.localStyleNum"
                                    :loading="updateLocalNumBtnLoading"
                                    >更新</el-button
                                >
                            </div>
                        </el-form-item>
                        <!-- 发行年 -->
                        <el-form-item
                            :label="`${il8n('faxingnian.label')}:`"
                            prop="issuanceYear"
                        >
                            <el-select
                                v-model="formData.issuanceYear"
                                :placeholder="`${il8n(
                                    'faxingnian.placeholder'
                                )}`"
                                style="width: 100%"
                                :clearable="true"
                                filterable
                            >
                                <el-option
                                    v-for="(
                                        item, index
                                    ) in dictOptions.issuanceYear"
                                    :key="index"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                        <!-- sbu -->
                        <el-form-item
                            :label="`${il8n('SBU.label')}:`"
                            prop="sbuNum"
                        >
                            <el-input
                                v-model="formData.sbuNum"
                                :clearable="true"
                                :placeholder="`${il8n('zidonghuoqu')}`"
                                disabled
                            />
                        </el-form-item>
                        <!-- 開辦順序 -->
                        <el-form-item
                            :label="`${il8n('kaibanshunxu.label')}:`"
                            prop="establishOrder"
                        >
                            <el-select
                                v-model="formData.establishOrder"
                                :placeholder="`${il8n(
                                    'kaibanshunxu.placeholder'
                                )}`"
                                style="width: 100%"
                                :clearable="true"
                                filterable
                                @change="establishOrderChange"
                            >
                                <el-option
                                    v-for="(
                                        item, index
                                    ) in dictOptions.establishOrder"
                                    :key="index"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                        <!-- 发行月 -->
                        <el-form-item
                            :label="`${il8n('faxingyue.label')}:`"
                            prop="issuanceMonth"
                        >
                            <el-select
                                v-model="formData.issuanceMonth"
                                :placeholder="`${il8n(
                                    'faxingyue.placeholder'
                                )}`"
                                style="width: 100%"
                                :clearable="true"
                                filterable
                            >
                                <el-option
                                    v-for="(
                                        item, index
                                    ) in dictOptions.issuanceMonth"
                                    :key="index"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                        <!-- 客户编号 -->
                        <el-form-item
                            :label="`${il8n('kehubianhao.label')}:`"
                            prop="cumstomerNum"
                        >
                            <el-input
                                v-model="formData.cumstomerNum"
                                :clearable="true"
                                :placeholder="`${il8n(
                                    'kehubianhao.placeholder'
                                )}`"
                                disabled
                            />
                        </el-form-item>
                        <!-- 架類材質 -->
                        <el-form-item
                            prop="frameMaterial"
                        >
                        <template #label>
                            <div class="cell-item">
                                <span style="color:red;">*</span>
                                {{ `${il8n('jingjiacaizhi.label')}` }}
                            </div>
                        </template>
                            <el-select
                                v-model="formData.frameMaterial"
                                :placeholder="`${il8n(
                                    'jingjiacaizhi.placeholder'
                                )}`"
                                style="width: 100%"
                                :clearable="true"
                                filterable
                                @change="frameMaterialsChange"
                            >
                                <el-option
                                    v-for="(
                                        item, index
                                    ) in dictOptions.frameMaterials"
                                    :key="index"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                        <!-- 绘图 -->
                        <el-form-item
                            :label="`${il8n('huitu.label')}:`"
                            prop="drawer"
                        >
                            <el-select
                                v-model="formData.drawer"
                                :placeholder="`${il8n('huitu.placeholder')}`"
                                style="width: 100%"
                                :clearable="true"
                                filterable
                                @change="drawerChange"
                            >
                                <el-option
                                    v-for="(item, index) in dictOptions.drawer"
                                    :key="index"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                        <!-- 業務類別 -->
                        <el-form-item
                            :label="`${il8n('yewuleibie.label')}:`"
                            prop="businessCate"
                        >
                            <el-select
                                v-model="formData.businessCate"
                                :placeholder="`${il8n(
                                    'yewuleibie.placeholder'
                                )}`"
                                style="width: 100%"
                                :clearable="true"
                                filterable
                            >
                                <el-option
                                    v-for="(
                                        item, index
                                    ) in dictOptions.businessCate"
                                    :key="index"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                        <!-- 客户款号 -->
                        <el-form-item
                            :label="`${il8n('kehukuanhao.label')}:`"
                            prop="customerStyleNum"
                        >
                            <el-input
                                v-model="formData.customerStyleNum"
                                :clearable="true"
                                :placeholder="`${il8n(
                                    'kehukuanhao.placeholder'
                                )}`"
                            />
                        </el-form-item>
                        <!-- 成本核算分類 -->
                        <el-form-item
                            :label="`${il8n('chengbenhesuan.label')}:`"
                            prop="costAccountCate"
                        >
                            <el-select
                                v-model="formData.costAccountCate"
                                :placeholder="`${il8n(
                                    'chengbenhesuan.placeholder'
                                )}`"
                                style="width: 100%"
                                :clearable="true"
                                filterable
                            >
                                <el-option
                                    v-for="(
                                        item, index
                                    ) in dictOptions.costAccountCate"
                                    :key="index"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                        <!-- 鉸鏈類別 -->
                        <el-form-item
                            :label="`${il8n('jiaolianleibie.label')}:`"
                            prop="hingeType"
                        >
                            <el-select
                                v-model="formData.hingeType"
                                :placeholder="`${il8n(
                                    'jiaolianleibie.placeholder'
                                )}`"
                                style="width: 100%"
                                :clearable="true"
                                filterable
                            >
                                <el-option
                                    v-for="(
                                        item, index
                                    ) in dictOptions.hingeType"
                                    :key="index"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item></el-form-item>
                        <!-- 客户品牌 -->
                        <el-form-item
                            :label="`${il8n('kehupinpai.label')}:`"
                            prop="customerBrand"
                        >
                            <el-input
                                v-model="formData.customerBrand"
                                :clearable="true"
                                :placeholder="`${il8n(
                                    'kehupinpai.placeholder'
                                )}`"
                                disabled
                            />
                        </el-form-item>
                        <!-- 款式資訊-類別 -->
                        <el-form-item
                            :label="`${il8n('jingjiajingpian.label')}:`"
                            prop="category"
                        >
                            <el-select
                                v-model="formData.category"
                                :placeholder="`${il8n(
                                    'jingjiajingpian.placeholder'
                                )}`"
                                style="width: 100%"
                                :clearable="true"
                                filterable
                            >
                                <el-option
                                    v-for="(
                                        item, index
                                    ) in dictOptions.styleCate"
                                    :key="index"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                        <!-- 脾頭切口位 -->
                        <el-form-item
                            :label="`${il8n('pitouqiekouwei.label')}:`"
                            prop="splenicHeadIncisionPosition"
                        >
                            <el-select
                                v-model="formData.splenicHeadIncisionPosition"
                                :placeholder="`${il8n(
                                    'pitouqiekouwei.placeholder'
                                )}`"
                                style="width: 100%"
                                :clearable="true"
                                filterable
                            >
                                <el-option
                                    v-for="(
                                        item, index
                                    ) in dictOptions.splenicHeadIncisionPosition"
                                    :key="index"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item></el-form-item>
                        <!-- 系列 -->
                        <el-form-item
                            :label="`${il8n('xilie.label')}:`"
                            prop="series"
                        >
                            <el-input
                                v-model="formData.series"
                                :clearable="true"
                                :placeholder="`${il8n('xilie.placeholder')}`"
                            />
                        </el-form-item>
                        <!-- 款式資訊-架類 -->
                        <el-form-item
                            :label="`${il8n('jingjiajiegou.label')}:`"
                            prop="frameCate"
                        >
                        <template #label>
                            <div class="cell-item">
                                <span style="color:red;">*</span>
                                {{ `${il8n('jingjiajiegou.label')}` }}
                            </div>
                        </template>
                            <el-select
                                v-model="formData.frameCate"
                                :placeholder="`${il8n(
                                    'jingjiajiegou.placeholder'
                                )}`"
                                style="width: 100%"
                                :clearable="true"
                                filterable
                            >
                                <el-option
                                    v-for="(
                                        item, index
                                    ) in dictOptions.frameCate"
                                    :key="index"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                        <!-- 工程师组长 -->
                        <el-form-item
                            :label="`${il8n('gongchengshizuzhang.label')}:`"
                            prop="peLeader"
                        >
                            <el-select
                                v-model="formData.peLeader"
                                :placeholder="`${il8n(
                                    'gongchengshizuzhang.placeholder'
                                )}`"
                                style="width: 100%"
                                :clearable="true"
                                filterable
                            >
                                <el-option
                                    v-for="(item, key) in peLeaderOptions"
                                    :key="key"
                                    :label="item.userName"
                                    :value="item.userName"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item></el-form-item>
                        <!-- 款式資訊-性別 -->
                        <el-form-item
                            :label="`${il8n('xingbie.label')}:`"
                            prop="gender"
                        >
                            <el-select
                                v-model="formData.gender"
                                :placeholder="`${il8n('xingbie.placeholder')}`"
                                style="width: 100%"
                                :clearable="true"
                                filterable
                            >
                                <el-option
                                    v-for="(
                                        item, index
                                    ) in dictOptions.productGender"
                                    :key="index"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>

                        <el-form-item
                            :label="`${il8n('shengchanbaojia.label')}:`"
                            prop="transferOrderRange"
                        >
                            <el-tree-select
                                v-model="formData.transferOrderRange"
                                :data="dictOptions.transferOrder"
                                multiple
                                :render-after-expand="false"
                                show-checkbox
                                style="width: 240px"
                            />
                        </el-form-item>
                        <!-- 设计师 -->
                        <el-form-item
                            :label="`${il8n('shejishi.label')}:`"
                            prop="designer"
                        >
                            <el-select
                                v-model="formData.designer"
                                :placeholder="`${il8n('shejishi.placeholder')}`"
                                style="width: 100%"
                                :clearable="true"
                                filterable
                            >
                                <el-option
                                    v-for="(item, key) in designerOptions"
                                    :key="key"
                                    :label="item.userName"
                                    :value="item.userName"
                                />
                            </el-select>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
            <div class="gva-form-box">
                <div class="w-form-box">
                    <div class="list-header">计划日期</div>
                    <PlansData ref="PlansDataRef" :formData="formData" />
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { getProjectPlanList } from "@/api/plmProjectPlan";
import {
    createProductStyles,
    deleteProductStyles,
    deleteProductStylesByIds,
    updateProductStyles,
    findProductStyles,
    getProductStylesList,
    generateProductStylesPlan,
    getGenLocalStyleNum,
} from "@/api/plmProductStyles";
import { getSbuProjectsList } from "@/api/plmSbuProjects";
import { getUserList } from "@/api/user";
import { findSbuData } from "@/api/confSbuData";
import PlansData from "./PlansData.vue";

// 全量引入格式化工具 请按需保留
import { formatDate } from "@/utils/format";

defineOptions({
    name: "plmProductStylesAdd",
});

// 自动获取字典
import { getDictFunc } from "@/utils/format";
import { useDict } from "@/utils/dictionary.js";
import { emitter } from "@/utils/bus.js";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { ref, reactive, onMounted, computed } from "vue";
import { useI18n } from "vue-i18n";

const { t: il8n } = useI18n();

const route = useRoute();
const router = useRouter();

const type = ref("");
const sbuTypesOptions = ref([]);
const loading = ref(false);
const sbuOptions = ref([]); // sbu列表
const customerOptions = ref([]); // 客户编号列表
const brandOptions = ref([]); // 品牌列表
const saveLoading = ref(false); // 保存草稿状态
const submitLoading = ref(false); // 确认提交状态

const formData = ref({});
const projectPlans = ref([]); // 计划日期

const projectListOptions = ref([]); // 项目编号列表

// 字典列表
const dictOptions = ref({
    establishOrder: [], //開辦順序
    drawer: [], // 绘图
    frameCate: [], // 款式資訊-架類
    styleCate: [], // 款式資訊-類別
    costAccountCate: [], //成本核算分類
    frameMaterials: [], //架類材質
    productGender: [], //款式資訊-性別
    splenicHeadIncisionPosition: [], //脾頭切口位
    hingeType: [], //鉸鏈類別
    businessCate: [], //業務類別
    issuanceMonth: [], //業務月
    issuanceYear: [], //業務年
    transferOrder: [], //转单
});
const peLeaderOptions = ref([]); // 工程师组长列表
const designerOptions = ref([]); // 设计师列表

const oldFrameMaterial = ref(""); // 旧镜架材质
const oldLocalStyleNum = ref(""); // 旧本厂款号
const oldLocalStyleNumObj = ref({}); // 旧本厂款号列表

// 验证规则
const rule = reactive({
    // projectNum: [{ required: true, message: "请输入项目编号", trigger: "blur" }],
    projectNum: [
        { required: true, message: "请选择项目编号", trigger: "change" },
    ],
    // frameMaterial: [
    //     { required: true, message: "请选择镜架材质", trigger: "change" },
    // ],
    // transferOrderRange: [{ required: true, message: "请选择生产报价", trigger: "change" }],
});

const elFormRef = ref();

const PlansDataRef = ref();

// 保存按钮
const save = async (status) => {
    if (status == "1" && !formData.value.frameMaterial) {
        ElMessage({
            type: "warning",
            message: "镜架材质不能为空",
        });
        return;
    }
    if (
        status == "1" &&
        (!formData.value.transferOrderRange ||
            formData.value.transferOrderRange.length == 0)
    ) {
        ElMessage({
            type: "warning",
            message: "生产报价不能为空",
        });
        return;
    }
    elFormRef.value?.validate(async (valid) => {
        if (!valid) return;
        let res;
        if (status === "0") saveLoading.value = true;
        if (status === "1") submitLoading.value = true;
        let submitForm = Object.assign({}, formData.value);
        submitForm["status"] = status;
        submitForm["projectPlans"] = PlansDataRef.value.projectPlans.map(
            (item) => {
                item["planned_completion_date"] = new Date(
                    item["planned_completion_date"]
                ).toJSON();
                item["planned_start_date"] = new Date(
                    item["planned_start_date"]
                ).toJSON();
                return item;
            }
        );

        // console.log(submitForm);
        switch (type.value) {
            case "create":
                res = await createProductStyles(submitForm);
                if (res.code === 0) {
                    ElMessage({
                        type: "success",
                        message: "创建成功",
                    });
                    emitter.emit("closeThisPage");
                    router.push({
                        path: `/layout/ProductStylesView`,
                        query: {
                            id: res.data.ID,
                            subTitle: "款" + res.data.styleNum,
                        },
                    });
                }
                break;
            case "update":
                res = await updateProductStyles(submitForm);
                break;
        }
        saveLoading.value = false;
        submitLoading.value = false;
        // if (res.code === 0) {
        //     emitter.emit("closeThisPage", { path: "/layout/productStyles" });
        //     ElMessage({
        //         type: "success",
        //         message: "创建成功",
        //     });
        // }
    });
};

// 查询项目编号列表
const remoteMethodProject = async (keyword) => {
    const table = await getSbuProjectsList({
        page: 1,
        pageSize: 30,
        projectNum: keyword ? keyword : undefined,
    });
    if (table.code === 0) {
        projectListOptions.value = table.data.list;
    }
};
// select 改变
const projectNumChange = async (num) => {
    console.log("改变", num);
    let index = projectListOptions.value.findIndex((item) => {
        return item.projectNum === num;
    });
    if (index != -1) {
        // sbu
        formData.value["sbuNum"] = projectListOptions.value[index].sbuName;
        // 客户编号
        formData.value["cumstomerNum"] =
            projectListOptions.value[index].customerName;
        // 客户品牌
        formData.value["customerBrand"] =
            projectListOptions.value[index].brandName;
        // 初始化数据
        findSbuDataFun(formData.value.sbuNum);
        formData.value["peLeader"] = "";
        formData.value["designer"] = "";
        designerOptions.value = [];
        peLeaderOptions.value = [];
    }
};

// 更新本厂款号
const getGenLocalStyleNumFun = () => {
    if (!formData.value.frameMaterial) {
        ElMessage({
            type: "warning",
            message: "请选择镜架材质再更新",
        });
        return;
    }
    if (!formData.value.projectNum) {
        ElMessage({
            type: "warning",
            message: "请选择项目编号",
        });
        return;
    }
    updateLocalNumBtnLoading.value = true;
    getGenLocalStyleNum({
        cumstomerNum: formData.value.cumstomerNum,
        frameMaterial: formData.value.frameMaterial,
    })
        .then((res) => {
            updateLocalNumBtnLoading.value = false;
            if (res.code == 0) {
                formData.value.localStyleNum = res.data.localStyleNum;
                oldFrameMaterial.value = formData.value.frameMaterial;
                updateLocalNumBtn.value = true;
                oldLocalStyleNumObj.value[formData.value.frameMaterial] =
                    formData.value.localStyleNum;
            }
        })
        .catch((err) => {
            updateLocalNumBtnLoading.value = false;
        });
};

const updateLocalNumBtn = ref(true); // 更新按钮状态
const updateLocalNumBtnLoading = ref(false);
const frameMaterialsChange = () => {
    // updateLocalNumBtn.value = false;
    if (oldLocalStyleNumObj.value[formData.value.frameMaterial]) {
        formData.value.localStyleNum =
            oldLocalStyleNumObj.value[formData.value.frameMaterial];
    } else {
        formData.value.localStyleNum = null;
    }
};

// 获取sbu信息
const findSbuDataFun = (sbuNum) => {
    findSbuData({ sbuName: sbuNum }).then((res) => {
        let list = [];
        if (!res.data.resbuData.member) return;
        list = res.data.resbuData.member.split(",").map((item) => {
            return { userName: item, label: item, value: item };
        });
        designerOptions.value = list;
        peLeaderOptions.value = list;
    });
};

// 开办顺序改变
const establishOrderChange = () => {
    PlansDataRef.value.establishOrderChange();
};
// 绘图改变
const drawerChange = () => {
    PlansDataRef.value.drawerChange();
};

// 初始化方法
const init = async () => {
    // 建议通过url传参获取目标数据ID 调用 find方法进行查询数据操作 从而决定本页面是create还是update 以下为id作为url参数示例
    if (route.query.id) {
        const res = await findProductStyles({ ID: route.query.id });
        if (res.code === 0) {
            formData.value = res.data.reproductStyles;
            type.value = "update";
        }
    } else {
        type.value = "create";
    }
    // sbuTypesOptions.value = await getDictFunc("sbuTypes");

    const dict = await useDict(
        "establishOrder",
        "drawer",
        "frameCate",
        "styleCate",
        "costAccountCate",
        "frameMaterials",
        "productGender",
        "splenicHeadIncisionPosition",
        "hingeType",
        "businessCate",
        "issuanceYear",
        "issuanceMonth",
        "transferOrder"
    );
    dictOptions.value = Object.assign(dictOptions.value, dict);
};

init();

onMounted(() => {
    
});
</script>

<style lang="scss" scoped>
@import url("@/style/common/common.scss");
.form-footer {
    text-align: center;
    padding: 20px;
    background: #fff;
}
</style>
